/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.approval.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.approval.constant.AuditStatusConstant;
import com.icinfo.cloud.provider.punish.approval.dto.ApprovalOpinionHisQueryDto;
import com.icinfo.cloud.provider.punish.approval.dto.AuditDetailDocumentQueryDto;
import com.icinfo.cloud.provider.punish.approval.dto.AuditQueryPageDto;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalFlowRelationMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalFlowRelation;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalWaitRecord;
import com.icinfo.cloud.provider.punish.approval.service.ICaseApprovalCompleteRecordService;
import com.icinfo.cloud.provider.punish.approval.vo.*;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppCaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseReasonMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseReasonMainRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.AppCaseBeforeDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 描述: 案件文书审批完成记录 case_approval_complete_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Transactional(rollbackFor = {Error.class, Exception.class})
@Slf4j
public class CaseApprovalCompleteRecordServiceImpl extends MyBatisServiceSupport implements ICaseApprovalCompleteRecordService {

    @Autowired
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;

    @Autowired
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;

    @Autowired
    private CaseApprovalFlowRelationMapper caseApprovalFlowRelationMapper;

    @Autowired
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Resource
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;


    @Autowired
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;

    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private IExecuteDocumentRecordService executeDocumentRecordService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;


    @Override
    public EachStageNumVo getStageCaseNum(AuditQueryPageDto auditQueryPageDto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        auditQueryPageDto.setApprovalUserName(userDTO.getRealName());
        if(StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())){
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        EachStageNumVo eachStageNumVo = null;
        if(Constant.STRING_1.equals(auditQueryPageDto.getIsApprovalCenter())){
            eachStageNumVo =  caseApprovalCompleteRecordMapper.getStageCaseCenterNum(auditQueryPageDto);
        }else{
            eachStageNumVo =  caseApprovalCompleteRecordMapper.getStageCaseNum(auditQueryPageDto);
        }

        eachStageNumVo.setTotal(eachStageNumVo.getActingNum() + eachStageNumVo.getAgreeNum() + eachStageNumVo.getReturnNum());
        return eachStageNumVo;
    }

    @Override
    public List<AuditInfoListVo> getOffAuditList(AuditQueryPageDto auditQueryPageDto) {
        if (auditQueryPageDto.getLength() > 200){
            throw new BusinessException("每页条数不能超过200");
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setApprovalUserName(userDTO.getRealName());
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        if(StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())){
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        List<AuditInfoListVo> list = null;
        if(Constant.STRING_1.equals(auditQueryPageDto.getIsApprovalCenter())){
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalCompleteRecordMapper.getOffAuditCenterList(auditQueryPageDto);
        }else{
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalCompleteRecordMapper.getOffAuditList(auditQueryPageDto);
        }

        for (AuditInfoListVo vo : list) {
            //4.caseType 翻译 案件类型:1简易程序  2一般程序  3快速办理
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            /*if (Constant.STRING_1.equals(vo.getCaseType())) {
                vo.setCaseType("简易程序");
            } else if (Constant.STRING_2.equals(vo.getCaseType())) {
                vo.setCaseType("一般程序");
            }
            if (Constant.STRING_3.equals(vo.getCaseType())) {
                vo.setCaseType("快速办理");
            }*/
            // 多案由处理
            Example example = new Example(CaseReasonMainRecord.class);
            example.createCriteria().andEqualTo("caseId",vo.getCaseId()).andEqualTo("status","1");
            List<CaseReasonMainRecord> records = caseReasonMainRecordMapper.selectByExample(example);
            StringJoiner stringJoiner = new StringJoiner(";");
            for (CaseReasonMainRecord record : records){
                stringJoiner.add(record.getCaseReasonName());
            }
            vo.setCaseReason(stringJoiner.toString());
        }

        return list;
    }

    @Override
    public List<AuditInfoChainLogVo> getAuditChain(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) throws ParseException {

        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
       /* if(Constant.STRING_1.equals(auditDetailDocumentQueryDto.getIsMerge())){
            //todo
            CaseMainDetailInfo caseMainDetailInfo=caseMainDetailInfoMapper.selectByPrimaryKey(auditDetailDocumentQueryDto.getCaseId());
            documentCatalogCode=getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
        }*/
        List<AuditInfoChainLogVo> result = new ArrayList<>();
        // 查询发起人节点
        // 当前文书审批状态
        CaseMainInfoVo caseMainInfoVo=caseMainInfoService.getCaseMainInfo(caseId);
        String handleType=caseMainInfoVo.getHandleType();
        CaseDocumentRecord caseDocumentRecord=null;
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords=null;
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords =null;
        String docId=auditDetailDocumentQueryDto.getDocumentId();
        if(StringUtils.isNotBlank(docId)) {
            caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(docId);
            Example completeExample = new Example(CaseApprovalCompleteRecord.class);
                completeExample.createCriteria().andEqualTo("caseId", caseId)
                        .andLike("documentId", "%"+documentCatalogCode+"%").andEqualTo("docId",docId).andNotEqualTo("approvalStatus",AuditStatusConstant.AUDIT_STATUS_RECALL);
            completeExample.orderBy("approvalTime").asc();
            completeExample.orderBy("approvalNum").asc();
            caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(completeExample);
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("docId",docId).andEqualTo("documentId", documentCatalogCode);
            caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(waitExample);
        }
        String partyId = auditDetailDocumentQueryDto.getPartyId();
        if(null==caseDocumentRecord) {
            Example exampleDocRed = new Example(CaseDocumentRecord.class);
            Example.Criteria criteria = exampleDocRed.createCriteria();
            if (StringUtils.isBlank(handleType) || !Constant.STRING_2.equals(handleType)) {
                criteria.andEqualTo("caseId", caseId).andLike("documentCatalogCode", "%"+documentCatalogCode+"%");
            } else {
                criteria.andEqualTo("caseId", caseId).andLike("documentCatalogCode", "%"+documentCatalogCode+"%");
                if (!ObjectUtils.isEmpty(partyId)) {
                    criteria.andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId());
                }
            }
            //criteria.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            criteria.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRed);
            if (caseDocumentRecords.isEmpty()) {
                //从app文书记录表查看是否存在
                AppCaseDocumentRecordDto dto = new AppCaseDocumentRecordDto();
                dto.setCaseId(caseId);
                if (!ObjectUtils.isEmpty(documentCatalogCode)) {
                    dto.setDocumentCatalogCode(documentCatalogCode);
                }
                List<AppCaseBeforeDocumentRecordVo> list = caseDocumentRecordService.getAppCaseBeforeDocumentRecordList(dto);
                if (!list.isEmpty() && list.size() > 0) {
                    for (AppCaseBeforeDocumentRecordVo appCaseBeforeDocumentRecordVo : list) {
                        CaseDocumentRecord record = new CaseDocumentRecord();
                        BeanUtils.copyProperties(appCaseBeforeDocumentRecordVo, record);
                        caseDocumentRecords.add(record);
                    }
                } else {
                    throw new BusinessException("未匹配到文书记录");
                }
            }
            caseDocumentRecord = caseDocumentRecords.get(0);
        }
        // 发起人节点
        AuditInfoChainLogVo first = new AuditInfoChainLogVo();
        first.setStageName("发起申请");
        // 查询已审核记录
        if(ObjectUtils.isEmpty(caseApprovalCompleteRecords)) {
            Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
            if (StringUtils.isBlank(handleType) || !Constant.STRING_2.equals(handleType)) {
                exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                        .andLike("documentId", "%"+documentCatalogCode+"%").andNotEqualTo("approvalStatus", AuditStatusConstant.AUDIT_STATUS_RECALL);
            } else {
                exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                        .andLike("documentId", "%"+documentCatalogCode+"%").andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId()).andNotEqualTo("approvalStatus", AuditStatusConstant.AUDIT_STATUS_RECALL);
            }
            exampleComplete.orderBy("approvalTime").asc();
            exampleComplete.orderBy("approvalNum").asc();
            caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
        }
        // 查询待审核记录
        if(ObjectUtils.isEmpty(caseApprovalWaitRecords) ) {
            Example exampleWait = new Example(CaseApprovalWaitRecord.class);
            if (StringUtils.isBlank(handleType) || !Constant.STRING_2.equals(handleType)) {
                exampleWait.createCriteria().andEqualTo("caseId", caseId).andLike("documentId", "%"+documentCatalogCode+"%");
            } else {
                exampleWait.createCriteria().andEqualTo("caseId", caseId).andLike("documentId", "%"+documentCatalogCode+"%").andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId());
            }
            caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(exampleWait);
        }
        if (caseApprovalWaitRecords.isEmpty() && caseApprovalCompleteRecords.isEmpty()){
            return result;
        }
        // pending  审批中  ，pass 审核完成通过，return 审核完成退回
        String pending = "pending";
        // 未提交状态
        String ns = "notSubmit";
        // 未提交不显示审批链
        if(StringUtils.isBlank(caseDocumentRecord.getDocumentAuditStatus()) || ns.equals(caseDocumentRecord.getDocumentAuditStatus())){
            return result;
        }
        // 生成发起人节点
        setFirstChainNode(result, first, caseApprovalCompleteRecords, caseApprovalWaitRecords,documentCatalogCode);
        Example exampleRelation = new Example(CaseApprovalFlowRelation.class);
        exampleRelation.createCriteria().andLike("documentCatalogCode", "%"+documentCatalogCode+"%").andEqualTo("isNowVersion", "1");
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseApprovalFlowRelationMapper.selectByExample(exampleRelation);
        if (StringUtils.isBlank(caseDocumentRecord.getDocumentAuditStatus()) || ns.equals(caseDocumentRecord.getDocumentAuditStatus())) {
            for (CaseApprovalFlowRelation relation : caseApprovalFlowRelations) {
                AuditInfoChainLogVo vo = new AuditInfoChainLogVo();
                vo.setStageName(relation.getApprovalRoleName());
                vo.setIsAudit("NO");
                vo.setIsOwnAudit("NO");
                result.add(vo);
            }
            return result;
        }
        // 拼接已审核节点
        setAlreadyNodes(result, caseApprovalCompleteRecords,auditDetailDocumentQueryDto.getDocumentCatalogCode());
        //审批中
        if (pending.equals(caseDocumentRecord.getDocumentAuditStatus())) {
            AuditInfoChainLogVo vo = new AuditInfoChainLogVo();
            vo.setStageName("等待审批");
            vo.setPersonName(caseApprovalWaitRecords.get(0).getApprovalUserName());
            vo.setIsAudit("NO");
            vo.setIsOwnAudit("NO");
            // 当前待审核人是否是当前用户
            UserDTO userDTO = UserUtil.getUserInfo();
            if (userDTO.getUserId().toString().equals(caseApprovalWaitRecords.get(0).getApprovalUserId())) {
                vo.setIsOwnAudit("YES");
            }
            // 环节时长
            String lastNodeAuditTime = result.get(result.size() - 1).getAuditTime();
            Date lastNodeAuditDate = DateUtils.parseDate(lastNodeAuditTime, "yyyy-MM-dd HH:mm:ss");
            String costTime = getDateTimeString(lastNodeAuditDate, new Date(), null);
            vo.setCurrentCostTime(costTime);
            CaseApprovalWaitRecord caseApprovalWaitRecord=caseApprovalWaitRecords.get(0);
            if(Constant.STRING_1.equals(caseApprovalWaitRecord.getIsAutoApproval())) {
                //CaseApprovalFlowRelation caseApprovalFlowRelation=caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecord.getFlowRelationId());
                long startTime = new Date().getTime();
                long addTime=caseApprovalWaitRecord.getAddTime().getTime();
                long time=startTime-addTime;
                int autoSurplusTime=Integer.valueOf(caseApprovalWaitRecord.getAutoTime())- (int)time / 1000;
                if(autoSurplusTime<0){
                    autoSurplusTime=0;
                }
                vo.setAutoSurplusTime(String.valueOf(autoSurplusTime));
                vo.setIsAutoApproval(Constant.STRING_1);
            }
            result.add(vo);
            //拼接未指定审批人节点
            exampleRelation.clear();
            CaseApprovalFlowRelation caseApprovalFlowRelation = caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecords.get(0).getFlowRelationId());
            if (caseApprovalFlowRelation == null) {
                log.error("未匹配到文书记录-getAuditChain,caseId:{},partyId:{},documentCatalogCode:{}",caseId,partyId,documentCatalogCode);
                throw new BusinessException("未匹配到文书记录-getAuditChain");
            }
            // 查询未审核配置信息
            String isMerge=caseApprovalWaitRecord.getIsMerge();
            if(Constant.STRING_1.equals(isMerge)){
                documentCatalogCode="DC1A0223300CFGZSPB000000001";
            }
            exampleRelation.createCriteria().andLike("documentCatalogCode", "%"+documentCatalogCode+"%").
                    andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId()).
                    andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andGreaterThan("approvalOrderNum",caseApprovalWaitRecords.get(0).getApprovalNum());
            exampleRelation.orderBy("approvalOrderNum").asc();
            caseApprovalFlowRelations = caseApprovalFlowRelationMapper.selectByExample(exampleRelation);
            for (CaseApprovalFlowRelation relation : caseApprovalFlowRelations) {
                AuditInfoChainLogVo noAppointNode = new AuditInfoChainLogVo();
                noAppointNode.setStageName(relation.getApprovalRoleName());
                noAppointNode.setIsAudit("NO");
                noAppointNode.setIsOwnAudit("NO");
                result.add(noAppointNode);
            }
            return result;
        }
        return result;
    }

    @Override
    public AuditInfoChainLogTopVo getAuditChainTop(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
        CaseMainInfoVo caseMainInfoVo=caseMainInfoService.getCaseMainInfo(caseId);
        String handleType=caseMainInfoVo.getHandleType();
        String pass = "pass";
        String rtn = "return";
        String ns = "notSubmit";
        ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = detailByDocumentCatalogCode.getDocumentKindCode();
        // 当前文书审批状态
        Example exampleDocRed = new Example(CaseDocumentRecord.class);
        Example.Criteria criteria = exampleDocRed.createCriteria();
        String partyId = auditDetailDocumentQueryDto.getPartyId();
        if (!ObjectUtils.isEmpty(auditDetailDocumentQueryDto.getDocumentId())) {
            criteria.andEqualTo("id", auditDetailDocumentQueryDto.getDocumentId());
        } else {
            if (StringUtils.isBlank(handleType) || !Constant.STRING_2.equals(handleType) || DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode);
            } else {
                criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode);
                if (!ObjectUtils.isEmpty(partyId)) {
                    criteria.andEqualTo("partyId", partyId);
                }
            }
            //criteria.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            criteria.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }
       List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRed);
        if (caseDocumentRecords.isEmpty()){
            //从app文书记录表查看是否存在
            AppCaseDocumentRecordDto dto = new AppCaseDocumentRecordDto();
            dto.setCaseId(caseId);
            if(!ObjectUtils.isEmpty(documentCatalogCode)){
                dto.setDocumentCatalogCode(documentCatalogCode);
            }
            List<AppCaseBeforeDocumentRecordVo> list = caseDocumentRecordService.getAppCaseBeforeDocumentRecordList(dto);
            if (!list.isEmpty() && list.size() > 0) {
                for (AppCaseBeforeDocumentRecordVo appCaseBeforeDocumentRecordVo : list) {
                    CaseDocumentRecord record = new CaseDocumentRecord();
                    BeanUtils.copyProperties(appCaseBeforeDocumentRecordVo,record);
                    caseDocumentRecords.add(record);
                }
            } else {
                throw new BusinessException("未匹配到文书记录");
            }
        }
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
        // 审批完成，添加最后节点信息
        AuditInfoChainLogTopVo vo = new AuditInfoChainLogTopVo();
        // 未提交没有头部
        if (StringUtils.isBlank(caseDocumentRecord.getDocumentAuditStatus()) || ns.equals(caseDocumentRecord.getDocumentAuditStatus())) {
            return vo;
        }
        // 审批中头部
        // 查询待审核记录
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords =new ArrayList<>();
        Example exampleWait = new Example(CaseApprovalWaitRecord.class);
        if (!ObjectUtils.isEmpty(auditDetailDocumentQueryDto.getDocumentId())) {
            exampleWait.createCriteria().andEqualTo("caseId", caseId).andEqualTo("docId", auditDetailDocumentQueryDto.getDocumentId()+"");
            caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(exampleWait);
        }
        if(ObjectUtils.isEmpty(caseApprovalWaitRecords)){
            exampleWait.clear();
            if(StringUtils.isBlank(handleType)||!Constant.STRING_2.equals(handleType)|| DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                exampleWait.createCriteria().andEqualTo("caseId", caseId).andLike("documentId", "%"+documentCatalogCode+"%");
            }else{
                if (!ObjectUtils.isEmpty(partyId)) {
                    exampleWait.createCriteria().andEqualTo("caseId", caseId).andLike("documentId", "%"+documentCatalogCode+"%").andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId());
                }else{
                    exampleWait.createCriteria().andEqualTo("caseId", caseId).andLike("documentId", "%"+documentCatalogCode+"%");
                }
            }
            caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(exampleWait);
        }
        if (!caseApprovalWaitRecords.isEmpty()) {
            CaseApprovalFlowRelation caseApprovalFlowRelation = caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecords.get(0).getFlowRelationId());
            vo.setStageName(caseApprovalFlowRelation.getApprovalRoleName());
            vo.setDeadlineDate(DateUtils.formatDate(caseApprovalWaitRecords.get(0).getApprovalCurrentPlanendTime(), "yyyy-MM-dd"));
            //截止时间- 当前时间
            vo.setRemainTime(getDateTimeString(new Date(),caseApprovalWaitRecords.get(0).getApprovalCurrentPlanendTime() , "YES"));
            return vo;
        }
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords=new ArrayList<>();
        Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
        if (!ObjectUtils.isEmpty(auditDetailDocumentQueryDto.getDocumentId())) {
            exampleComplete.createCriteria().andEqualTo("caseId", caseId).andEqualTo("docId", auditDetailDocumentQueryDto.getDocumentId());
            caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
        }
        if(ObjectUtils.isEmpty(caseApprovalCompleteRecords)){
            exampleComplete.clear();
            if(StringUtils.isBlank(handleType)||!Constant.STRING_2.equals(handleType)) {
                exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                        .andLike("documentId", "%"+documentCatalogCode+"%");
            }else{
                exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                        .andLike("documentId", "%"+documentCatalogCode+"%").andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId());
            }
            exampleComplete.orderBy("approvalNum").asc();
            caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
        }


        if (caseApprovalCompleteRecords.isEmpty()){
            return vo;
        }
        // 最后审核时间-提交时间
        Date date1 = caseApprovalCompleteRecords.get(0).getAddTime();
        Date date2 = caseApprovalCompleteRecords.get(caseApprovalCompleteRecords.size() - 1).getApprovalTime();
        String costAllTime = getDateTimeString(date1, date2, null);
        //审批完成头部
        if (pass.equals(caseDocumentRecord.getDocumentAuditStatus())) {
            vo.setStageName("审批通过");
            vo.setRemainTime(costAllTime);
        }
        if (rtn.equals(caseDocumentRecord.getDocumentAuditStatus())) {
            vo.setStageName("审批退回");
            vo.setRemainTime(costAllTime);
        }
        return vo;
    }

    @Override
    public AuditInfoVo getAuditDocDetail(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        AuditInfoVo auditInfoVo = new AuditInfoVo();
        if(Constant.STRING_1.equals(auditDetailDocumentQueryDto.getIsMerge())){
            auditInfoVo=getAuditInfoVoMerge(auditDetailDocumentQueryDto);
            return auditInfoVo;
        }
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentId = auditDetailDocumentQueryDto.getDocumentId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
        //查询待审批记录
        Example example=new Example(CaseApprovalWaitRecord.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo("documentId",documentCatalogCode)
                .andEqualTo("caseId",caseId);
        if(StrUtil.isNotEmpty(documentId)){
            criteria.andEqualTo("docId", documentId);
        }
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords=caseApprovalWaitRecordMapper.selectByExample(example);
        if(!ObjectUtils.isEmpty(caseApprovalWaitRecords)){
            documentId=caseApprovalWaitRecords.get(0).getDocId();
        }
        auditInfoVo.setCaseId(caseId);
        auditInfoVo.setDocumentCatalogCode(documentCatalogCode);
        // 查询记录表
        Example exampleDoc = new Example(CaseDocumentRecord.class);
        if(StringUtils.isNotBlank(documentId)){
            exampleDoc.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", documentId);
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }else if(StringUtils.isNotBlank(auditDetailDocumentQueryDto.getPartyId())){
            exampleDoc.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId())
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }else{
            exampleDoc.createCriteria().andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode)
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDoc);
        if(!ObjectUtils.isEmpty(documentId) && (ObjectUtils.isEmpty(caseDocumentRecords) || caseDocumentRecords.size() == 0) ){
            //从app文书记录表查看是否存在
            AppCaseDocumentRecordDto dto = new AppCaseDocumentRecordDto();
            dto.setCaseId(caseId);
            dto.setDocumentId(documentId);
            if(!ObjectUtils.isEmpty(documentCatalogCode)){
                dto.setDocumentCatalogCode(documentCatalogCode);
            }
            List<AppCaseBeforeDocumentRecordVo> list = caseDocumentRecordService.getAppCaseBeforeDocumentRecordList(dto);
            if (!list.isEmpty() && list.size() > 0) {
                AppCaseBeforeDocumentRecordVo vo = list.get(0);
                auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrl());
                if (StringUtils.isNotEmpty(vo.getDocumentUrlAfterSeal())) {
                    auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrlAfterSeal());
                }
                if (StringUtils.isNotEmpty(vo.getDocumentUrlAfterSign())) {
                    auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrlAfterSign());
                }
            }
        }
        if (!caseDocumentRecords.isEmpty() && caseDocumentRecords.size() > 0) {
            auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrl());
            auditInfoVo.setCaseAssistId(caseDocumentRecords.get(0).getCaseAssistId());
            if (StringUtils.isNotEmpty(caseDocumentRecords.get(0).getDocumentUrlAfterSeal())) {
                auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(caseDocumentRecords.get(0).getDocumentUrlAfterSign())) {
                auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrlAfterSign());
            }
        }

        // 查询配置表
        Example exampleBusinessParam = new Example(ConfigBusiParamDocumentInfo.class);
        exampleBusinessParam.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
        if (configBusiParamDocumentInfos.isEmpty()) {
            return auditInfoVo;
        }
        auditInfoVo.setCurrentNodeDocumentName(configBusiParamDocumentInfos.get(0).getDocumentKindName());
        if(DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(configBusiParamDocumentInfos.get(0).getDocumentKindCode())){
            Example documentRecordExample = new Example(CaseDocumentRecord.class);
            documentRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("relationApprovalDocumentId", documentId);
            List<CaseDocumentRecord> relationRecord = caseDocumentRecordMapper.selectByExample(documentRecordExample);
            if(ObjectUtil.isNotEmpty(relationRecord)){
                auditInfoVo.setCurrentLinkDocumentUrl(relationRecord.get(0).getDocumentUrl());
                //查询名称
                ConfigBusiParamDocumentInfo relationConfig = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationRecord.get(0).getDocumentCatalogCode());
                auditInfoVo.setCurrentLinkDocumentName(relationConfig.getDocumentCatalogName());
            }
            return auditInfoVo;
        }
        // 设置关联文书
        if (StringUtils.isNotBlank(configBusiParamDocumentInfos.get(0).getRelationDocumentCatalogCode())) {
            String[] relationDoc = configBusiParamDocumentInfos.get(0).getRelationDocumentCatalogCode().split(",");
            exampleDoc.clear();
            // 查询关联文书地址
            if(StringUtils.isBlank(auditDetailDocumentQueryDto.getPartyId())){
                exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc))
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }else{
                exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc)).andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId())
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }
            List<CaseDocumentRecord> relationsDocs = caseDocumentRecordMapper.selectByExample(exampleDoc);
            if (!relationsDocs.isEmpty()) {
                StringJoiner stringJoiner = new StringJoiner(",");
                List<String> relationDocCode = new ArrayList<>();
                for (CaseDocumentRecord record : relationsDocs) {
                    // 只查询已生成文书
                    if (StringUtils.isNotBlank(record.getDocumentUrl())){
                        // 如果关联文书是抽样取证通知书时，查询已签字的文书地址
                        if (!ObjectUtils.isEmpty(record.getDocumentTemplateCode()) && "APPTMPCYQZTZS".equals(record.getDocumentTemplateCode())) {
                            if (!ObjectUtils.isEmpty(record.getDocumentUrlAfterSeal())) {
                                stringJoiner.add(record.getDocumentUrlAfterSeal());
                            } else {
                                stringJoiner.add(record.getDocumentUrl());
                            }
                        } else {
                            stringJoiner.add(record.getDocumentUrl());
                        }
                        relationDocCode.add(record.getDocumentCatalogCode());
                    }
                }
                auditInfoVo.setCurrentLinkDocumentUrl(stringJoiner.toString());
                // 查询关联文书名称
                if(relationDocCode.size()>0){
                    exampleBusinessParam.clear();
                    exampleBusinessParam.createCriteria().andIn("documentCatalogCode", relationDocCode);
                    List<ConfigBusiParamDocumentInfo> relations = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
                    if (!relations.isEmpty()) {
                        StringJoiner stringJoiner1 = new StringJoiner(",");
                        for (ConfigBusiParamDocumentInfo param : relations) {
                            stringJoiner1.add(param.getDocumentKindName());
                        }
                        auditInfoVo.setCurrentLinkDocumentName(stringJoiner1.toString());
                    }
                }
            }
        }
        return auditInfoVo;
    }
    /**
     * 获取审批文书
     * @author liyafeng
     * @date 2023/4/25
      * @param auditDetailDocumentQueryDto
     * @return {@link AuditInfoVo}
     */
    private AuditInfoVo getAuditInfoVoMerge(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        AuditInfoVo auditInfoVo=new AuditInfoVo();
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentId = auditDetailDocumentQueryDto.getDocumentId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
        //查询待审批记录
        Example example=new Example(CaseApprovalWaitRecord.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo("documentId",documentCatalogCode)
                .andEqualTo("caseId",caseId);
        if(StrUtil.isNotEmpty(documentId)){
            criteria.andEqualTo("docId", documentId);
        }
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords=caseApprovalWaitRecordMapper.selectByExample(example);
        if(!ObjectUtils.isEmpty(caseApprovalWaitRecords)){
            documentId=caseApprovalWaitRecords.get(0).getDocId();
        }
        auditInfoVo.setCaseId(caseId);
        auditInfoVo.setDocumentCatalogCode(documentCatalogCode);
        //合并审批循环遍历文书目录编码
        String[] documentCatalogCodeArr=auditDetailDocumentQueryDto.getDocumentCatalogCode().split(Constant.STRING_COMMA);
        if(ObjectUtils.isEmpty(documentCatalogCodeArr)){
            throw new BusinessException("文书目录编码传参异常");
        }
        List<String> documentCatalogCodeList=Arrays.asList(documentCatalogCodeArr);
        for (String catalogCode:documentCatalogCodeList) {
            // 查询记录表
            Example exampleDoc = new Example(CaseDocumentRecord.class);
            if(StringUtils.isNotBlank(auditDetailDocumentQueryDto.getPartyId())){
                exampleDoc.createCriteria().andEqualTo("caseId", caseId)
                        .andEqualTo("documentCatalogCode", catalogCode).andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId())
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }else{
                exampleDoc.createCriteria().andEqualTo("caseId", caseId)
                        .andEqualTo("documentCatalogCode", catalogCode)
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }
            // 查询配置表
            Example exampleBusinessParam = new Example(ConfigBusiParamDocumentInfo.class);
            exampleBusinessParam.createCriteria().andEqualTo("documentCatalogCode", catalogCode);
            List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
            if (configBusiParamDocumentInfos.isEmpty()) {
                return auditInfoVo;
            }

            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDoc);
            if (!caseDocumentRecords.isEmpty() && caseDocumentRecords.size() > 0&&catalogCode.contains(DocumentKindEnum.DOC_KIND_LASPB.getCode())) {
                auditInfoVo.setCurrentNodeDocumentName(configBusiParamDocumentInfos.get(0).getDocumentKindName());
                auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrl());
                auditInfoVo.setCaseAssistId(caseDocumentRecords.get(0).getCaseAssistId());
                if (StringUtils.isNotEmpty(caseDocumentRecords.get(0).getDocumentUrlAfterSeal())) {
                    auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrlAfterSeal());
                }
                if (StringUtils.isNotEmpty(caseDocumentRecords.get(0).getDocumentUrlAfterSign())) {
                    auditInfoVo.setCurrentNodeTableUrl(caseDocumentRecords.get(0).getDocumentUrlAfterSign());
                }
                //立案审批表不查询关联文书直接退出循环
                continue;
            }else {
                // 设置关联文书
                String relationDocumentCatalogCoder = "DC2A0223300ZJBG000000000001," +catalogCode+","+ configBusiParamDocumentInfos.get(0).getRelationDocumentCatalogCode();
                String[] relationDocumentCatalogCoderArr=relationDocumentCatalogCoder.split(Constant.STRING_COMMA);
                List<String> relationDocumentCatalogCodeList=Arrays.asList(relationDocumentCatalogCoderArr);
                StringJoiner stringJoiner = new StringJoiner(",");
                StringJoiner stringJoiner1 = new StringJoiner(",");
                for (String relationDocumentCatalogCode:relationDocumentCatalogCodeList) {
                    exampleDoc.clear();
                    // 查询关联文书地址
                    if (StringUtils.isBlank(auditDetailDocumentQueryDto.getPartyId())) {
                        exampleDoc.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", relationDocumentCatalogCode)
                                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    } else {
                        exampleDoc.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", relationDocumentCatalogCode).andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId())
                                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    }
                    List<CaseDocumentRecord> relationsDocs = caseDocumentRecordMapper.selectByExample(exampleDoc);
                    exampleBusinessParam.clear();
                    exampleBusinessParam.createCriteria().andEqualTo("documentCatalogCode", relationDocumentCatalogCode);
                    List<ConfigBusiParamDocumentInfo> relations = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
                    if(!ObjectUtils.isEmpty(relationsDocs)&&!ObjectUtils.isEmpty(relations)){
                        stringJoiner.add(relationsDocs.get(Constant.INTEGER_0).getDocumentUrl());
                        stringJoiner1.add(relations.get(0).getDocumentKindName());
                    }
                }
                auditInfoVo.setCurrentLinkDocumentUrl(stringJoiner.toString());
                auditInfoVo.setCurrentLinkDocumentName(stringJoiner1.toString());
                /*if (StringUtils.isNotBlank(relationDocumentCatalogCoder)) {
                    String[] relationDoc = relationDocumentCatalogCoder.split(",");
                    exampleDoc.clear();
                    // 查询关联文书地址
                    if (StringUtils.isBlank(auditDetailDocumentQueryDto.getPartyId())) {
                        exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc))
                                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    } else {
                        exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc)).andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId())
                                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                    }
                    List<CaseDocumentRecord> relationsDocs = caseDocumentRecordMapper.selectByExample(exampleDoc);
                    if (!relationsDocs.isEmpty()) {
                        StringJoiner stringJoiner = new StringJoiner(",");
                        List<String> relationDocCode = new ArrayList<>();
                        for (CaseDocumentRecord record : relationsDocs) {
                            // 只查询已生成文书
                            if (StringUtils.isNotBlank(record.getDocumentUrl())) {
                                stringJoiner.add(record.getDocumentUrl());
                                relationDocCode.add(record.getDocumentCatalogCode());
                            }
                        }
                        auditInfoVo.setCurrentLinkDocumentUrl(stringJoiner.toString());
                        // 查询关联文书名称
                        if (relationDocCode.size() > 0) {
                            exampleBusinessParam.clear();
                            exampleBusinessParam.createCriteria().andIn("documentCatalogCode", relationDocCode);
                            List<ConfigBusiParamDocumentInfo> relations = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
                            if (!relations.isEmpty()) {
                                StringJoiner stringJoiner1 = new StringJoiner(",");
                                for (ConfigBusiParamDocumentInfo param : relations) {
                                    stringJoiner1.add(param.getDocumentKindName());
                                }
                                auditInfoVo.setCurrentLinkDocumentName(stringJoiner1.toString());
                            }
                        }
                    }
                }*/
            }
        }

        return auditInfoVo;
    }

    /**
     *查询历史审批内容
     * @author liyafeng
     * @date 2022/7/11
      * @param dto
     * @return {@link List< String>}
     */
    @Override
    public List<String> getApprovalOpinionHis(ApprovalOpinionHisQueryDto dto) {
        UserDTO userDTO=UserUtil.getUserInfo();
        Map<String,Object> paramMap=new HashMap<>();
        if(dto.getApprovalStatus().equals(AuditStatusConstant.AUDIT_STATUS_WAIT)){
            paramMap.put("addUserId",userDTO.getUserId().toString());
            paramMap.put("approvalUserId","");
        }else{
            paramMap.put("addUserId","");
            paramMap.put("approvalUserId",userDTO.getUserId().toString());
        }
        paramMap.put("approvalStatus",dto.getApprovalStatus());
        paramMap.put("documentId",dto.getDocumentCatalogCode());
        List<String> approvalOpinions=caseApprovalCompleteRecordMapper.selectApprovalOpinionHis(paramMap);
        if(StringUtils.isNotBlank(dto.getType())&&dto.getApprovalStatus().equals(AuditStatusConstant.AUDIT_STATUS_WAIT)){
            try {
                List<String> approvalOpinionSingles=new ArrayList<>();
                if(!ObjectUtils.isEmpty(approvalOpinions)){
                    for (String approvalOpinion:approvalOpinions) {
                        if(approvalOpinion.startsWith("{")) {
                            JSONObject opinionJsonObject = JSONObject.parseObject(approvalOpinion);
                            String opinion = "";
                            if (Constant.STRING_1.equals(dto.getType())) {
                                opinion = opinionJsonObject.getString("opinion");
                            } else if (Constant.STRING_2.equals(dto.getType())) {
                                opinion = opinionJsonObject.getString("informOpinion");
                            }
                            approvalOpinionSingles.add(opinion);
                        }else{
                            approvalOpinionSingles.add(approvalOpinion);
                        }

                    }
                }
                return approvalOpinionSingles;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return approvalOpinions;
    }

    @Override
    public List<AuditInfoListVo> getApprovedList(AuditQueryPageDto auditQueryPageDto) {
        if (auditQueryPageDto.getLength() > 200){
            throw new BusinessException("每页条数不能超过200");
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setApprovalUserName(userDTO.getRealName());
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        if(StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())){
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        List<AuditInfoListVo> list = null;
        if(Constant.STRING_1.equals(auditQueryPageDto.getIsApprovalCenter())){
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalCompleteRecordMapper.getOffAuditCenterList(auditQueryPageDto);
        }else{
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalCompleteRecordMapper.selectApprovalList(auditQueryPageDto);
        }
        return list;
    }

    @Override
    public EachStageNumVo getStageNum(AuditQueryPageDto auditQueryPageDto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        auditQueryPageDto.setApprovalUserName(userDTO.getRealName());
        if(StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())){
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        EachStageNumVo eachStageNumVo = null;
        if(Constant.STRING_1.equals(auditQueryPageDto.getIsApprovalCenter())){
            eachStageNumVo =  caseApprovalCompleteRecordMapper.getStageCaseCenterNum(auditQueryPageDto);
        }else{
            eachStageNumVo =  caseApprovalCompleteRecordMapper.selectStageNum(auditQueryPageDto);
        }

        eachStageNumVo.setTotal(eachStageNumVo.getActingNum() + eachStageNumVo.getAgreeNum() + eachStageNumVo.getReturnNum());
        return eachStageNumVo;
    }


    public void setAlreadyNodes(List<AuditInfoChainLogVo> result, List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords,String documentCatalogCode) {
        String zero = "0";
        String start = "start";
        String rtr = "return";
        for (CaseApprovalCompleteRecord completeRecord : caseApprovalCompleteRecords) {
            if (!zero.equals(completeRecord.getApprovalNum())){
                AuditInfoChainLogVo vo = new AuditInfoChainLogVo();
                vo.setStageName("审批完成");
                if(rtr.equals(completeRecord.getApprovalStatus())){
                    vo.setStageName("审批退回");
                }
                vo.setPersonName(completeRecord.getApprovalUserName());
                vo.setAuditTime(DateUtils.formatDate(completeRecord.getApprovalTime(), "yyyy-MM-dd HH:mm:ss"));
                if(Constant.STRING_1.equals(completeRecord.getIsMerge())&&Constant.STRING_3.equals(completeRecord.getApprovalNum())&&AuditStatusConstant.AUDIT_STATUS_AGREE.equals(completeRecord.getApprovalStatus())) {
                    CaseDocumentRecord caseDocumentRecord=caseDocumentRecordService.getCaseDocumentRecord(completeRecord.getCaseId(),documentCatalogCode);
                    if(!ObjectUtils.isEmpty(caseDocumentRecord)&&null!=caseDocumentRecord.getDocumentApprovalTime()){
                        vo.setAuditTime(caseDocumentRecord.getDocumentApprovalTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    }
                }
                vo.setIsAudit("YES");
                vo.setIsOwnAudit("NO");
                vo.setOpinion(completeRecord.getApprovalOpinion());
                if (StringUtils.isNotBlank(completeRecord.getApprovalBackType())){
                    vo.setReturnDesc("上一环节");
                    if (start.equals(completeRecord.getApprovalBackType())){
                        vo.setReturnDesc("退回发起人");
                    }
                }
                result.add(vo);
            }
        }
    }

    /**
     * 两个时间 间隔中文描述
     *
     * @param lastNodeAuditDate
     * @param preFlag
     * @return
     */
    public String getDateTimeString(Date lastNodeAuditDate, Date date, String preFlag) {
        String costTime = "";
        Long seconds = (date.getTime() - lastNodeAuditDate.getTime()) / 1000;
        String flag = "剩";
        if (seconds < 0) {
            seconds = (-seconds);
            flag = "超";
        }
        int days = (int) (seconds / 60 / 60 / 24);
        //不足一天的小时
        int hours;
        // 不足一小时分钟
        int minutes;
        if (days >= 1) {
            seconds = seconds - 60 * 60 * 24 * days;
            hours = (int) (seconds / 60 / 60);
            seconds = seconds - 60 * 60 * hours;
            minutes = (int) (seconds / 60);
            costTime = costTime + days + "天" + hours + "时" + minutes + "分";
        }
        if (days < 1) {
            hours = (int) (seconds / 60 / 60);
            if (hours > 1) {
                seconds = seconds - 60 * 60 * hours;
                minutes = (int) (seconds / 60);
                costTime = hours + "时" + minutes + "分";
            } else {
                minutes = (int) (seconds / 60);
                costTime = minutes + "分";
            }
        }
        if (StringUtils.isNotBlank(preFlag)) {
            costTime = flag + costTime;
        }
        return costTime;
    }

    public void setFirstChainNode(List<AuditInfoChainLogVo> result, AuditInfoChainLogVo first, List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords, List<CaseApprovalWaitRecord> caseApprovalWaitRecords,String documentCatalogCode) {
        if (!caseApprovalCompleteRecords.isEmpty()) {
            CaseApprovalCompleteRecord caseApprovalCompleteRecord = caseApprovalCompleteRecords.get(0);
            first.setAuditTime(DateUtils.formatDate(caseApprovalCompleteRecord.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
            if(Constant.STRING_1.equals(caseApprovalCompleteRecord.getIsMerge())){
                try {
                    String opinionJsonString=caseApprovalCompleteRecord.getApprovalOpinion();
                    JSONObject opinionJsonObject= JSONObject.parseObject(opinionJsonString);
                    String opinion="";
                    if(documentCatalogCode.contains("LASPB")){
                        opinion=opinionJsonObject.getString("opinion");
                    }else{
                        opinion=opinionJsonObject.getString("informOpinion");
                    }
                    first.setOpinion(opinion);
                }catch (Exception e){
                    first.setOpinion(caseApprovalCompleteRecord.getApprovalOpinion());
                }
            }else{
                first.setOpinion(caseApprovalCompleteRecord.getApprovalOpinion());
            }
            first.setPersonName(caseApprovalCompleteRecord.getAddUserName());
            first.setIsAudit("YES");
            first.setIsOwnAudit("NO");
            result.add(first);
        } else {
            //如果为空，从待审批表取
            if (!caseApprovalWaitRecords.isEmpty()) {
                first.setAuditTime(DateUtils.formatDate(caseApprovalWaitRecords.get(0).getAddTime(), "yyyy-MM-dd HH:mm:ss"));
                first.setPersonName(caseApprovalWaitRecords.get(0).getAddUserName());
                first.setIsAudit("YES");
                first.setIsOwnAudit("NO");
                result.add(first);
            } else {
                throw new BusinessException("待审批记录为空-setFirstChainNode");
            }
        }
    }
    @Override
    public AuditInfoVo getAuditDocDetailWithExecute(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        AuditInfoVo auditInfoVo = new AuditInfoVo();
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentId = auditDetailDocumentQueryDto.getDocumentId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();


        auditInfoVo.setCaseId(caseId);
        auditInfoVo.setDocumentCatalogCode(documentCatalogCode);
        // 查询记录表
        Example exampleDoc = new Example(ExecuteDocumentRecord.class);
        if(StringUtils.isNotBlank(documentId)){
            exampleDoc.createCriteria().andEqualTo("executeId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", documentId)
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }else if(StringUtils.isNotBlank(auditDetailDocumentQueryDto.getPartyId())){
            exampleDoc.createCriteria().andEqualTo("executeId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId())
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }else{
            exampleDoc.createCriteria().andEqualTo("executeId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode)
                    //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        }
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDoc);
        /*if(!ObjectUtils.isEmpty(documentId) && (ObjectUtils.isEmpty(executeDocumentRecords) || executeDocumentRecords.size() == 0) ){
            //从app文书记录表查看是否存在
            AppCaseDocumentRecordDto dto = new AppCaseDocumentRecordDto();
            dto.setCaseId(caseId);
            dto.setDocumentId(documentId);
            if(!ObjectUtils.isEmpty(documentCatalogCode)){
                dto.setDocumentCatalogCode(documentCatalogCode);
            }
            List<AppCaseBeforeDocumentRecordVo> list = caseDocumentRecordService.getAppCaseBeforeDocumentRecordList(dto);
            //List<AppExecuteBeforeDocumentRecordVo> list = executeDocumentRecordService.getAppExecuteBeforeDocumentRecordList(dto);

            if (!list.isEmpty() && list.size() > 0) {
                AppCaseBeforeDocumentRecordVo vo = list.get(0);
                auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrl());
                if (StringUtils.isNotEmpty(vo.getDocumentUrlAfterSeal())) {
                    auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrlAfterSeal());
                }
                if (StringUtils.isNotEmpty(vo.getDocumentUrlAfterSign())) {
                    auditInfoVo.setCurrentNodeTableUrl(vo.getDocumentUrlAfterSign());
                }
            }
        }*/
        if (!executeDocumentRecords.isEmpty() && executeDocumentRecords.size() > 0) {
            auditInfoVo.setCurrentNodeTableUrl(executeDocumentRecords.get(0).getDocumentUrl());
            if (StringUtils.isNotEmpty(executeDocumentRecords.get(0).getDocumentUrlAfterSeal())) {
                auditInfoVo.setCurrentNodeTableUrl(executeDocumentRecords.get(0).getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(executeDocumentRecords.get(0).getDocumentUrlAfterSign())) {
                auditInfoVo.setCurrentNodeTableUrl(executeDocumentRecords.get(0).getDocumentUrlAfterSign());
            }
        }

        // 查询配置表
        Example exampleBusinessParam = new Example(ConfigBusiParamDocumentInfo.class);
        exampleBusinessParam.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
        if (configBusiParamDocumentInfos.isEmpty()) {
            return auditInfoVo;
        }
        auditInfoVo.setCurrentNodeDocumentName(configBusiParamDocumentInfos.get(0).getDocumentKindName());
        // 设置关联文书
        if (StringUtils.isNotBlank(configBusiParamDocumentInfos.get(0).getRelationDocumentCatalogCode())) {
            String[] relationDoc = configBusiParamDocumentInfos.get(0).getRelationDocumentCatalogCode().split(",");
            exampleDoc.clear();
            // 查询关联文书地址
            if(StringUtils.isBlank(auditDetailDocumentQueryDto.getPartyId())){
                exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc))
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }else{
                exampleDoc.createCriteria().andEqualTo("caseId", caseId).andIn("documentCatalogCode", Arrays.asList(relationDoc)).andEqualTo("partyId",auditDetailDocumentQueryDto.getPartyId())
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
            }
            List<ExecuteDocumentRecord> relationsDocs = executeDocumentRecordMapper.selectByExample(exampleDoc);
            if (!relationsDocs.isEmpty()) {
                StringJoiner stringJoiner = new StringJoiner(",");
                List<String> relationDocCode = new ArrayList<>();
                for (ExecuteDocumentRecord record : relationsDocs) {
                    // 只查询已生成文书
                    if (StringUtils.isNotBlank(record.getDocumentUrl())){
                        stringJoiner.add(record.getDocumentUrl());
                        relationDocCode.add(record.getDocumentCatalogCode());
                    }
                }
                auditInfoVo.setCurrentLinkDocumentUrl(stringJoiner.toString());
                // 查询关联文书名称
                exampleBusinessParam.clear();
                exampleBusinessParam.createCriteria().andIn("documentCatalogCode", relationDocCode);
                List<ConfigBusiParamDocumentInfo> relations = configBusiParamDocumentInfoMapper.selectByExample(exampleBusinessParam);
                if (!relations.isEmpty()) {
                    StringJoiner stringJoiner1 = new StringJoiner(",");
                    for (ConfigBusiParamDocumentInfo param : relations) {
                        stringJoiner1.add(param.getDocumentKindName());
                    }
                    auditInfoVo.setCurrentLinkDocumentName(stringJoiner1.toString());
                }
            }
        }
        return auditInfoVo;
    }

    private String getMergeDocumentCatalogCode(String investConclusion) {
        String documentCatalogCode="DC1A0223300CFGZSPB000000001";
        if(Constant.STRING_2.equals(investConclusion)){
            documentCatalogCode="DC1A0223300BYCFGZSPB0000001";
        }
        return documentCatalogCode;
    }
}
